# -*- coding: utf-8 -*-

'''
/**
 * @addtogroup esm_gen_base_c_source
 * esm_gen_base_c_source
 * @{
 */
/**
 * @file        esm_gen_base_c_source.py
 * @brief       XXXX
 * @note        XXXX
 * @author      靳普诏(puzhao.jin@hopechart.com)
 * @date        2023/08/26
 * @version     1.0

 * @par         修改日志
 * <table>
 * <tr><th>Date         <th>Version     <th>Author      <th> Description
 * <tr><td>2023/08/26   <td>1.0         <td>靳普诏       <td> 创建初始版本
 * @copyright   xxxx
 */
'''

import sys
import os
import datetime

from pyazlib.EasyJinja2 import *
from esm_get_table_info import *


g_current_datetime = datetime.datetime.now()
g_cur_time = g_current_datetime.strftime('%Y-%m-%d %H:%M:%S')
g_cur_date = g_current_datetime.strftime('%Y/%m/%d')


class TEsmGenCCode:
    def __init__(self, esm_info: TEsmTableInfo, tpl_folder:str):
        # jinja2对象        
        self.tpl = TEasyJinja2(tpl_folder)
        
        self.__esm_info = esm_info
        # 把条件函数名全部拿出来
        self.cond_func_list = []
        
        for state in esm_info.esm_state_list:
            for cond in state.cond_list:
                cond_func_info = TEsmCondFuncInfo(cond[1], cond[2])
                need_add = True
                for cond_item in self.cond_func_list:
                    if cond_item.function_name == cond_func_info.function_name:
                        cond_item.brief += (";" + cond_func_info.brief)
                        need_add = False
                        break
                if need_add:
                    self.cond_func_list.append(cond_func_info)
        pass

    def __GenStateFuncListCode(self):
        ret_code = ""

        for state in self.__esm_info.esm_state_list:
            ret_code += self.__GenOneStateFuncCode(state) + "\n"

        return ret_code


    def __GenOneStateFuncCode(self, state_func_info: TEsmStateFuncInfo):
        ret_code = ""

        code_dict = {}
        code_dict["j2_proj_name"] = self.GetCfgInfo("工程代码名")
        code_dict["j2_state_name"] = state_func_info.function_name
        code_dict["j2_state_func_name"] = self.__GenStateFuncName(state_func_info.function_name)
        code_dict["j2_state_skip_code"] = self.__GenStateSkipCode(state_func_info)
        code_dict["j2_func_brief"] = state_func_info.brief
        ret_code = self.tpl.Render(code_dict, "state_function_tpl.c.j2")

        return ret_code




    def __GenCondFuncListCode(self):
        ret_code = ""

        for cond in self.cond_func_list:
            ret_code += self.__GenOneCondFuncCode(cond) + "\n"

        return ret_code

    def __GenOneCondFuncCode(self, cond: TEsmCondFuncInfo):
        ret_code = ""

        code_dict = {}
        code_dict["j2_proj_name"] = self.GetCfgInfo("工程代码名")
        code_dict["j2_cond_name"] = cond.function_name
        code_dict["j2_cond_func_name"] = self.__GenCondFuncName(cond.function_name)
        code_dict["j2_func_brief"] = cond.brief
        ret_code = self.tpl.Render(code_dict, "cond_function_tpl.c.j2")

        return ret_code

    def __GenStateFuncName(self, tag: str):
        proj_name = self.GetCfgInfo("工程代码名")
        state_name = tag
        ret_code = f"L_T{proj_name}On{state_name}Process"

        return ret_code

    def __GenCondFuncName(self, tag: str):
        proj_name = self.GetCfgInfo("工程代码名")
        cond_name = tag
        ret_code = f"L_T{proj_name}Cond{cond_name}"

        return ret_code

    def __GenStateSkipCode(self, state_func_info: TEsmStateFuncInfo):
        ret_code = ""

        state_func_info.Sort()

        if len(state_func_info.cond_list) > 0:
            cond_func_name = self.__GenCondFuncName(state_func_info.cond_list[0][1])
            state_func_name = self.__GenStateFuncName(state_func_info.cond_list[0][3])
            ret_code += f"    if ({cond_func_name}(self, user_param))\n"
            ret_code += f"        self->state_function_ = {state_func_name};\n"
            for cond in state_func_info.cond_list[1:]:
                cond_func_name = self.__GenCondFuncName(cond[1])
                state_func_name = self.__GenStateFuncName(cond[3])
                ret_code += f"    else if ({cond_func_name}(self, user_param))\n"
                ret_code += f"        self->state_function_ = {state_func_name};\n"

        return ret_code

    def GenCode(self):
        out_file = self.GetCfgInfo("目标目录名") + "/" + self.GetCfgInfo("目标文件名")
        cond_code = self.__GenCondFuncListCode()
        state_code = self.__GenStateFuncListCode()


        code_dict = {}
        code_dict["var_filename"] = self.GetCfgInfo("目标文件名")
        code_dict["var_author"] = self.GetCfgInfo("作者")
        code_dict["var_email"] = self.GetCfgInfo("邮箱")
        code_dict["var_version"] = self.GetCfgInfo("版本")
        code_dict["var_time"] = g_cur_time
        code_dict["var_proj_name"] = self.GetCfgInfo("工程代码名")
        code_dict["var_cond_code"] = cond_code
        code_dict["var_state_code"] = state_code
        
        self.tpl.Render(code_dict, "state_machine_main.c.j2", out_file + '.c')
        self.tpl.Render(code_dict, "state_machine_main.h.j2", out_file + '.h')

    def GetCfgInfo(self, key: str):
        return self.__esm_info.config_info_dict[key]


if __name__ == "__main__":
    ## 获取当前脚本所在的目录
    SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
    # 输出目录路径
    print("SCRIPT_DIR: "+ SCRIPT_DIR)

    ## 获取脚本传参
    argv = sys.argv
    argc = len(argv)
    # 打印命令行参数
    #for i in range(1, argc):
        #print("参数", i, ":", argv[i])
        
    print("============= BIGEN: esm_gen_base_c_source.py =============")




    print("============= END: esm_gen_base_c_source.py =============")



## Generated on "2023-08-26 21:16:23" by the tool "gen_hq_file.py >> V20230509_1" 